#include "frame_builder.h"

// 乒乓缓冲区
uint8_t frame1Buffer1[FRAME_TOTAL_SIZE_1];
uint8_t frame1Buffer2[FRAME_TOTAL_SIZE_1];
uint8_t frame2Buffer1[FRAME_TOTAL_SIZE_2];
uint8_t frame2Buffer2[FRAME_TOTAL_SIZE_2];
uint8_t frame1_flag = 0; // 第一个帧的缓冲区标志
uint8_t frame2_flag = 0; // 第二个帧的缓冲区标志
uint8_t dist_buffer[3] = {0};
uint16_t frame_count = 0;

void SoftVersion(uint8_t *data)
{
    unsigned short temp_crc = 0;
    temp_crc = crc16(data, 10);
    data[10] = (uint8_t)(temp_crc & 0xFF);
    data[11] = (uint8_t)(temp_crc >> 8);
}

// 组帧函数
void BuildFrame2(const uint8_t *sgm_dev1, const uint8_t *sgm_dev2, const uint8_t *controller)
{
    uint8_t *frame;

    // 选择当前缓冲区
    frame = (frame2_flag == 0) ? frame2Buffer1 : frame2Buffer2;

    // 1. 帧头部分
    frame[0] = 0xEB;
    frame[1] = 0x90;
    frame[2] = 0xA3;
    frame[3] = 0x1A;

    // 2. 有效数据部分
    frame[4] = sgm_dev2[7];
    frame[5] = sgm_dev2[6];
    frame[6] = sgm_dev1[1];
    frame[7] = sgm_dev2[5];
    frame[8] = controller[1];
    frame[9] = sgm_dev1[5];
    frame[10] = sgm_dev2[4];
    frame[11] = sgm_dev1[4];
    frame[12] = sgm_dev1[0];
    frame[13] = sgm_dev1[3];
    frame[14] = controller[2];
    frame[15] = sgm_dev1[6];
    frame[16] = controller[3];
    frame[17] = sgm_dev1[7];
    frame[18] = controller[4];
    frame[19] = sgm_dev2[0];
    frame[20] = controller[5];
    frame[21] = sgm_dev2[1];
    frame[22] = controller[6];
    frame[23] = sgm_dev2[2];
    frame[24] = sgm_dev1[2];
    frame[25] = controller[0];
    
    frame2_flag = 1 - frame2_flag;
}

// 获取组好的帧数据
uint8_t *GetFrame2(void)
{
    uint8_t *frame;

    // 选择当前缓冲区
    if (frame2_flag == 0)
    {
        frame = frame2Buffer1;
    }
    else
    {
        frame = frame2Buffer2;
    }

    // 返回当前帧数据
    return frame;
}


// 组帧函数（第一个帧）
void BuildFrame1(uint8_t data1, uint8_t data2, uint8_t data3, uint8_t data4)
{
    uint8_t *frame;

    // 选择当前缓冲区
    frame = (frame1_flag == 0) ? frame1Buffer1 : frame1Buffer2;

    // 1. 帧头部分
    frame[0] = 0xEB;
    frame[1] = 0x90;
    frame[2] = 0xA2;
    frame[3] = 0x06;

    // 2. 有效数据部分
    frame[4] = data1;
    frame[5] = data2;
    frame[6] = data3;
    frame[7] = data4;

    // 3. 固定部分
    frame[8] =  (uint8_t)(frame_count >> 8);
    frame[9] = (uint8_t)(frame_count & 0xFF);

    // 4. 计算 CRC16 校验


    // 切换缓冲区标志
    frame1_flag = 1 - frame1_flag;
}

// 获取组好的帧数据（第一个帧）
uint8_t *GetFrame1(void)
{
    uint8_t *frame;

    // 选择当前缓冲区
    if (frame1_flag == 0)
    {
        frame = frame1Buffer1;
    }
    else
    {
        frame = frame1Buffer2;
    }

    // 返回当前帧数据
    return frame;
}